package com.weidft.web.wd.controller;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.roma.core.annotations.Form;
import com.alibaba.roma.core.form.validation.Errors;
import com.alibaba.roma.web.multipart.MultipartFile;
import com.alibaba.roma.web.servlet.result.View;
import com.alibaba.roma.web.servlet.result.WebResult;
import com.weidft.biz.picture.PictureNamespaceType;
import com.weidft.biz.picture.PictureService;
import com.weidft.dal.craft.dataobject.StorageDO;
import com.weidft.dal.craft.dto.PictureUploadDTO;

public class UploadController extends Basic {
	public WebResult showPicture(Map model, Errors errors, String action,
			String id) {
		if (errors.hasErrors()) {
			// return new Redirect("searchYhc.htm");
		}
		Integer picId = new Integer(0);
		try {
			picId = Integer.parseInt(id);
		} catch (NumberFormatException nfe) {
		}

		StorageDO storageDo = yhcManager.getStorageDao().findSimpleStorageById(
				picId);
		String displayPicName = null;
		String rootPath = getRootPath();
		
		if (storageDo != null) {
			displayPicName = storageDo.getFilename();
			PictureService pictureService = yhcManager.getPictureService();
			if (!pictureService.fileExist(displayPicName, rootPath)) {
				storageDo = yhcManager.getStorageDao().findById(picId);
				pictureService.createFileByFullname(storageDo.getStorage(),
						displayPicName, rootPath);
			}
		}

		return null;
	}

	@Form(group = "pictureUploadForm", checkCsrf = false, checkFormResubmit = false)
	public WebResult uploadFile(Map<String, Object> model,
			PictureUploadDTO pictureUploadDTO,String prefix) {
		MultipartFile pictureFile = pictureUploadDTO.getPictureFile();
		int picId = 0;
		String path = "";

		if (pictureFile != null
				&& StringUtils.isNotEmpty(pictureFile.getOriginalFilename())) {

			path = yhcManager.getPictureService().constructFileName(
					pictureFile.getOriginalFilename(),
					PictureNamespaceType.groove);

			StorageDO storageDO = new StorageDO();
			storageDO.setFilename(path);
			storageDO.setState(StorageDO.PIC);
			try {
				storageDO.setStorage(pictureFile.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}

			picId = yhcManager.getStorageDao().insert(storageDO).intValue();
			if (!pictureService.fileExist(path,getRootPath())) {
				try
				{
					pictureService.createFileByFullname(pictureFile.getBytes(),path, getRootPath());
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
		final int pId = picId;
		final String picturePath = path;
		model.put("success", pId > 0 ? Boolean.TRUE : Boolean.FALSE);
		model.put("picId", pId);
		model.put("picPath", picturePath);
		return new View("/wd/upload/uploadresult.htm");
	}

}
